package device

import "encoding/json"

// 设备与家庭信息的绑定
type bindController struct{}

type bindInfo struct {
	HomeId   string `json:"home"`
	Firmware string `json:"firmware"`
	Date     string `json:"date"`
}

func (b *bindController) handle(w *reception, msg *Message) error {
	if msg.Method == MsgMethodPut {
		var info bindInfo
		err := json.Unmarshal(msg.Data, &info)
		if err != nil {
			return err
		}

		// 更新家庭信息或者固件版本
		if w.register.HomeId != info.HomeId || w.register.FirmwareRevision != info.Firmware {
			w.register.HomeId = info.HomeId
			w.register.FirmwareRevision = info.Firmware
			w.register.Save()
		}

		pkg := &MessagePkg{
			DevId:  w.register.Id,
			HomeId: w.register.HomeId,
			Msg: &Message{
				Path:   MsgPathContainerInfo,
				Method: MsgMethodPut,
				State:  ContainerStateOnline,
			},
		}

		workers.rpkg <- pkg
		return nil
	}
	return nil
}

func init() {
	deviceMsgHandleMap[msgPathBindInfo] = &bindController{}
}
